package com.goodboys.base.interceptor;

import com.alibaba.fastjson.JSON;
import com.goodboys.base.resp.Response;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class BaseInterceptorConfig implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(BaseInterceptorConfig.class);

    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        logger.info("---------------------开始进入请求地址拦截----------------------------");
        Response msg = new Response();
        //逻辑判断
        try {
            //获取是lat,lng字段
            String lat = request.getParameter("lat");
            String lng = request.getParameter("lng");

            if (StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)) {
                //经纬度存在为空，报错
                msg.failure("经纬度存在为空,请重试。。。");
                sendMessage(response, msg);
                logger.warn("经纬度存在为空,请重试。。。");
                return false;
            }else {
                return  true;
            }

        } catch (NullPointerException e) {
            //经纬度存在为空，报错
            msg.failure("经纬度存在为空,请重试。。。");
            sendMessage(response,msg);
            logger.warn("经纬度存在为空,请重试。。。");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("---------------视图渲染之后的操作-------------------------0");
    }


    /**
     * 发送消息 text/html;charset=utf-8
     * @param response
     * @param obj
     * @throws Exception
     */
    public static void sendMessage(HttpServletResponse response, Object obj) throws Exception {
        response.setContentType("text/html; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(obj));
        writer.close();
        response.flushBuffer();
    }

}
